package br.ufrn.imd.classificados.tasks;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

/**
 * HTTP PUT requests to the REST API.
 * @author Reginaldo Silva
 *
 */
public class ApiPutTask extends AsyncTask<JSONObject, Void, Boolean> {

	String endpoint;

	public ApiPutTask(String endpoint) {
		this.endpoint = endpoint;		
	}

	protected Boolean doInBackground(JSONObject... params) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPut request = new HttpPut("http://arcane-atoll-4224.herokuapp.com/" + this.endpoint);

        try {
	        StringEntity entity = new StringEntity(params[0].toString());
	        entity.setContentType("application/json;charset=UTF-8");
	        entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
	        request.setEntity(entity);
	        httpClient.execute(request);
		} catch (UnsupportedEncodingException e) {
	    	e.printStackTrace();
	        Log.i("Unsupported Encoding Exception", e + "");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			Log.i("Client Protocol Exception", e + "");
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("IO Exception", e + "");
		}
      	return true;
	}
}
